/**
 * Created by ZHOUSH on 3/7/2016.
 */
app.factory('draggingService', function ($rootScope, $q, $timeout) {
    // factory function body that constructs shinyNewServiceInstance
    var draggingItem = $('<div class="dragging-item"></div>');
    var isDragging = false;
    var draggingOffset = {
        dx: 0,
        dy: 0
    };
    $(function () {
        $('body').append(draggingItem);
        draggingItem.hide();
    });
    function pauseEvent(e){
        if(e.stopPropagation) e.stopPropagation();
        if(e.preventDefault) e.preventDefault();
        e.cancelBubble=true;
        e.returnValue=false;
        return false;
    }
    $('body')
        .on('mousemove', function (event) {
            if (isDragging) {
                pauseEvent(event || window.event);
                draggingItem.css({
                    top: event.clientY - draggingOffset.dy,
                    left: event.clientX - draggingOffset.dx
                })
            }
        })
        .on('mouseup', function (event) {
            if (isDragging) {
                //pauseEvent(event || window.event);
                isDragging = false;
                draggingItem.hide();
                draggingItem.removeClass('dragging');
                draggingItem.removeClass('dragging-treeview').addClass('treeview');
            }
        });
    return {
        treeview: function ($treeview, fn) {
            $treeview
                .on('mousedown', function (event) {
                    var item = $(event.target);
                    var nodeid = item.attr('data-nodeid');
                    var tv = $($treeview).data();
                    var node = tv.treeview.getNode(nodeid);
                    if (node['draggable']) {
                        //pauseEvent(event || window.event);
                        draggingItem.show();
                        draggingItem.empty().append(item.children().clone()).append(item.text())
                        var pos = item.offset();
                        draggingOffset.dx = event.clientX - pos.left;
                        draggingOffset.dy = event.clientY - pos.top;
                        draggingItem.addClass('dragging-treeview').addClass('treeview')
                        draggingItem.css({
                            top: event.clientY - draggingOffset.dy,
                            left: event.clientX - draggingOffset.dx,
                            width: item.outerWidth(),
                            height: item.outerHeight()
                        });
                        isDragging = true;
                    }
                    tv.treeview.selectNode(node);
                })
                .on('mouseup', function (event) {

                })
        }
    };
});